package com.hotai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotai.comment.dtos.PageResponseResult;
import com.hotai.comment.dtos.ResponseResult;
import com.hotai.comment.enums.AppHttpCodeEnum;
import com.hotai.comment.enums.AppJwtUtil;
import com.hotai.comment.md5.MD5Utils;
import com.hotai.comment.pojo.*;
import com.hotai.mapper.CoursewareMapper;
import com.hotai.mapper.InstitutionMapper;
import com.hotai.mapper.UserTeacherMapper;
import com.hotai.service.UserService;
import com.hotai.service.UserTeacherService;
import com.hotai.vo.courseware.Coursewaredetaile;
import com.hotai.vo.equipment.EquipmentList;
import com.hotai.vo.sho.TearSho;
import com.hotai.vo.sho.TearShoList;
import com.hotai.vo.user.LoginDto;
import com.hotai.vo.userteacher.*;
import com.hotai.vo.usestudent.UserStudentDetailePage;
import net.minidev.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

@Service
public class UserTeacherServiecImpl extends ServiceImpl<UserTeacherMapper, UserTeacher> implements UserTeacherService {
    @Autowired
    private UserTeacherMapper  userTeacherMapper;
    @Autowired
    private InstitutionMapper institutionMapper;

    private static final String Salt = "MHCDEKLDE321";


    @Override
    public ResponseResult login(LoginDto dto) {

        if( (StringUtils.isEmpty(dto.getPassword())&&StringUtils.isEmpty(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.手机号+密码登录
        if(!StringUtils.isEmpty(dto.getUsername())&&!StringUtils.isEmpty(dto.getPassword())){
            //用户登录
            UserTeacher dbUser = userTeacherMapper.selectOne(Wrappers.<UserTeacher>lambdaQuery().eq(UserTeacher::getUsername, dto.getUsername()));
            if (dbUser!=null) {
//                String pswd = DigestUtils.md5DigestAsHex((dto.getPassword()+dbUser.getSalt()).getBytes());
                if (dbUser.getStatus()==2){
                    return ResponseResult.errorResult(506, "该账号被限制无法登录");
                }
                if (dbUser.getDeid()==2){
                    return ResponseResult.errorResult(506, "该账号已被删除");
                }
                if (dbUser.getPassword().equals(dto.getPassword())) {
                    Map<String, Object> map = new HashMap<>();
//                    dbUser.setPassword("");
//                    dbUser.setSalt("");
                    dbUser.setDengluDate(new Date());
                    userTeacherMapper.updateById(dbUser);
                    map.put("token", AppJwtUtil.getToken(dbUser.getId().longValue()));
//                    map.put("user", dbUser);
                    return ResponseResult.okResult(map);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        }
      return    null;

    }

    @Override
    public ResponseResult EuipmentPage(EquipmentList query) {
        //参数为空
        if (query==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        query.checkParam();
        query.setPage((query.getPage()-1)*query.getSize());

        ArrayList<UserTeacherPageLIst> detaile = userTeacherMapper.detaile(query);
        PageResponseResult responseResult = new PageResponseResult(query.getPage()+1,query.getSize(), detaile.size());
        responseResult.setData(detaile);
        return responseResult;
    }

    @Override
    public ResponseResult GuanTeaList(EquipmentList query) {
        //参数为空
        if (query==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        query.checkParam();
        LambdaQueryWrapper<UserTeacher> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (query!=null){
            lambdaQueryWrapper.like(StringUtils.isNotBlank(query.getName()),UserTeacher::getName,query.getName())
                              .eq(UserTeacher::getDeid,1);
        }
        Page page2 = new Page(query.getPage(),query.getSize());
        IPage page = page(page2, lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(query.getPage(),query.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return  responseResult;
    }

    @Override
    public ResponseResult GuanTeaDetail(EquipmentList query) {
        //参数为空
        if (query==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        query.checkParam();

        query.setPage((query.getPage()-1)*query.getSize());
        ArrayList<GuanTeachDetablie> detaile = userTeacherMapper.Guandetaile(query);
        PageResponseResult responseResult = new PageResponseResult(query.getPage()+1,query.getSize(), detaile.size());
        responseResult.setData(detaile);
        return responseResult;
    }

    @Override
    public ResponseResult GuanTeaShoDetail(GuanTeacherPage query) {
        //参数为空
        if (query==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        query.checkParam();

        query.setPage((query.getPage()-1)*query.getSize());


//        if (query.getName()==null){
//            ArrayList<GuanTearShoDetablie> detaile = userTeacherMapper.GuanShoDetale(query);
//            for (GuanTearShoDetablie guanTearShoDetablie : detaile) {
//                query.setName(guanTearShoDetablie.getCname());
//                break;
//            }
//
//        }

        ArrayList<GuanTearShoDetablie> detaile2 = userTeacherMapper.GuanShoDetale(query);


        PageResponseResult responseResult = new PageResponseResult(query.getPage()+1,query.getSize(), detaile2.size());
        responseResult.setData(detaile2);
        return responseResult;
    }


    @Override
    public ResponseResult TeacherDetail(GuanTeacherPageList query) {
        //参数为空
        if (query==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        query.checkParam();
        query.setPage((query.getPage()-1)*query.getSize());
        if ( query.getDa()==null){
            query.setDa(7);
        }
        ArrayList<CourseTeacher> detaile = userTeacherMapper.Xuedetaile(query);
        PageResponseResult responseResult = new PageResponseResult(query.getPage()+1,query.getSize(), detaile.size());
        responseResult.setData(detaile);
        return responseResult;
    }

    @Override
    public ResponseResult TeacherJinBenDetail(Integer id) {
        ArrayList<UserTeacherJin> detaile=userTeacherMapper.JinBanTea(id);
       return ResponseResult.okResult(detaile);

    }

    @Override
    public ResponseResult XiuGaiTead(TeaXiuGai teaXiuGai) {
        if (teaXiuGai.getPasswrod().equals(teaXiuGai.getPasswrod2())){
            userTeacherMapper.XIuGai(teaXiuGai);
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());

        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
    }

    @Override
    public ResponseResult XiuGaiTeadPhone(TeaXiuGai teaXiuGai) {
        userTeacherMapper.XiuPhone(teaXiuGai);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult Daochu(HttpServletRequest request, HttpServletResponse response) {
        JSONObject result=new JSONObject();
        try {
            //准备数据
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("老师");
            //课程
            HSSFRow row = sheet.createRow(0);
            int num = 0;
            //创建第一行第一个单元格
            HSSFCell cell = row.createCell(num++);
            cell.setCellValue("用户名");
            cell = row.createCell(num++);
            cell.setCellValue("所属机构");
//            cell = row.createCell(num++);
//            cell.setCellValue("操作");
            //下载文件
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
//
//            response.setHeader("content-disposition",
//                    "attachment;filename=" + java.net.URLEncoder.encode("老师.xls", "UTF-8")
//                            + ";filename*=utf-8''" + java.net.URLEncoder.encode("老师.xls", "UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("老师.xls", "UTF-8"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/octet-stream");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PQCG, AppHttpCodeEnum.PQCG.getErrorMessage());
    }

    @Override
    public ResponseResult improtStu(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        try {
            HSSFWorkbook workbook2 = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet2 = workbook2.getSheet("老师");
            int lastRowNum2 = sheet2.getLastRowNum();

            ArrayList<UserTearImplAdd> userTeachers = new ArrayList<>();
            for (int i = 1; i <= lastRowNum2; i++) {
                UserTearImplAdd emp2 = new UserTearImplAdd();
                HSSFRow row = sheet2.getRow(i);
                int num=0;
                HSSFCell cell = row.getCell(num++);
                String name = cell.getStringCellValue();
                String iname = row.getCell(num++).getStringCellValue();
                if (!iname.equals("个人")){
                    Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName,iname));
                    if (institution==null){
                        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前机构不存在");
                    }
                }
                    emp2.setName(name);
                    emp2.setIname(iname);
                    emp2.setTime(new Date());
                    userTeachers.add(emp2);
            }
            return  ResponseResult.okResult(userTeachers);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult TeacherChonzhe(Integer id) {
         userTeacherMapper.chongzhi(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    @Override
    public ResponseResult TeaShoPage(TearSho query) {
        //参数为空
        if (query==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        query.checkParam();
        query.setPage((query.getPage()-1)*query.getSize());

        ArrayList<TearShoList> detaile = userTeacherMapper.TearShoPage(query);
        PageResponseResult responseResult = new PageResponseResult(query.getPage()+1,query.getSize(), detaile.size());
        responseResult.setData(detaile);
        return responseResult;
    }

    @Override
    public ResponseResult improtAdd(TearImprot tearImprot) {
        ArrayList<UserTearImplAdd> userTearImplAdds = tearImprot.getUserTearImplAdds();
        for (UserTearImplAdd userTearImplAdd : userTearImplAdds) {
            UserTeacher userTeacher = new UserTeacher();

            //用户是否存在
            UserTeacher userStudentPhone = userTeacherMapper.selectOne(Wrappers.<UserTeacher>lambdaQuery().eq(UserTeacher::getName, userTearImplAdd.getName()));
            if (userStudentPhone != null) {
                throw new RuntimeException("用户名重复");
            }

            if (userTearImplAdd.getIname().equals("个人")){
                userTeacher.setSid(null);
            }else {
                Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName, userTearImplAdd.getIname()));
                userTeacher.setSid(institution.getId());
            }
            userTeacher.setName(userTearImplAdd.getName());
            userTeacher.setDeid(1);
            userTeacher.setPassword(MD5Utils.encodeWithSalt("000000", Salt));
            userTeacher.setSalt(Salt);
//            userTeacher.setUsername(suiji());
            userTeacher.setStatus(1);
            userTeacher.setCreateDate(new Date());
            userTeacherMapper.insert(userTeacher);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    @Override
    public ResponseResult UpdateSheXian(Integer id) {
        userTeacherMapper.TeaXian(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult UpdateSheXuan(String ide) {
        String[] split = ide.split(",");
        for (String s : split) {
            userTeacherMapper.TeaXian(Integer.parseInt(s));
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult InstitlinTear(InstitlionTear institlionTear) {
        UserTeacher userTeacher = new UserTeacher();
        userTeacher.setZhename(institlionTear.getZhename());
        userTeacher.setSid(institlionTear.getId());
        userTeacher.setName(suiji());
        userTeacher.setSalt(Salt);
        userTeacher.setPassword(MD5Utils.encodeWithSalt("000000", Salt));
        userTeacher.setDeid(1);
        userTeacher.setStatus(1);
        userTeacher.setCreateDate(new Date());
        userTeacherMapper.insert(userTeacher);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    private  String  suiji(){
        Random random = new Random();
        String result="";
        for (int i=0;i<10;i++)
        {
            result+=random.nextInt(10);
        }

        return  result;
    }

}
